<template>
  <el-row type="flex" class="info-container">

    <div class="info-inner" v-if="currentUser">
      <el-card class="box-card info-card">
        <el-row type="flex" class="user-profile">
          <el-col>
            <userWrapper class="group" v-if="isGroup" :avatar="groupInfo.avatar" :info="'群成员'+groupInfo.personNum+' 非好友'+ Math.max(groupInfo.friendNum,0)">
              <div class="name-wrap" slot="title">
                <div class="textEllipsis name">{{currentUser.friendNick||'群聊天'}}</div>
                <a v-if="isGroup && currentUser.isfirst===1" href="javascript:" @click="editGroup(currentUser)" class="edit-group">[修改]</a>
              </div>
            </userWrapper>
            <el-row type="flex" class="friend" v-else>
              <el-avatar shape="square" :size="40" fit="cover" :src="currentUser.avatar"></el-avatar>
              <el-col class="user-info">
                <div :class="['userBasicInfo',
                  currentUser.gender == 1 && currentUser.type=='user' ? 'male' :
                  currentUser.gender == 0 && currentUser.type=='user' ? 'femal' : '']">
                  {{currentUser.friendNick||currentUser.friendremark}}
                </div>
                <div class="userRegionInfo"><span class="fontGrey">地区</span>{{currentUser.region}}</div>
              </el-col>

            </el-row>
          </el-col>
        </el-row>
        <el-row class="source">
          <span>来&emsp;源：</span>{{source}}
        </el-row>
        <el-row class="wxid" v-if="isGroup">
          <span>群&emsp;主：</span>{{source}}
        </el-row>
        <el-row class="wxid">
          <span>WXID: </span>{{currentUser.friendwxid}}<el-link type="primary" @click="copy(currentUser.friendwxid,$event)">[复制]</el-link>
        </el-row>
        <el-row class="wxid">
          <span>微信号：</span>{{currentUser.friendAlias||currentUser.friendalias||currentUser.friendwxid}}
        </el-row>

      </el-card>

      <el-card class="box-card mark-card">
        <div slot="header" class="clearfix box-card-header mark-card-header">
          <span>备注</span>
          <el-button class="mark-button" type="primary" size="mini" @click="saveUserMark">保存</el-button>
        </div>
        <el-input type="textarea" v-model="mark"></el-input>
      </el-card>

      <el-card class="box-card tag-card">
        <div slot="header" class="clearfix box-card-header tag-card-header ">
          <span>标签</span>
          <el-button class="mark-button"
          type="primary" size="mini" @click="showEditLabelDialog" icon="el-icon-plus">添加</el-button>
        </div>
        <div class="tags" style="line-height:24px;">
          <span v-if="currentUser.isTop!==2 && !labels.length">
            暂无
          </span>
          <el-tag
            class="tag"
            v-if="currentUser.isTop===2"
            :disable-transitions="true"
            effect="dark"
            size="mini">
              VIP
          </el-tag>
          <el-tag
            class="tag"
            :key="item.id"
            :disable-transitions="true"
            v-for="(item) in labels"
            closable
            effect="dark"
            size="mini"
            @close="deleteLabel(item)"
          >
              {{item.tagName}}
          </el-tag>
        </div>
      </el-card>

      <quick-replies
        :csid="currentUser.csid"
        :wxid="currentUser.wxaccount"
        @click="quickClick"
      />
    </div>


    <modal name="tagDialog"
        transition="nice-modal-fade"
        overlayTransition="overlay-fade"
        draggable=".el-card__header" :width="372" height="auto">
        <el-card>
          <div slot="header" style="display: flex; flex-direction: row;justify-content: space-between;">
            <span>添加标签</span>
            <i class="el-icon-close" @click.stop="$modal.hide('tagDialog')"></i>
          </div>
          <el-form ref="form" label-width="70px">
              <el-form-item label="标签">
                <el-input maxlength="8" placeholder="" value="" clearable  v-model="editingLabel"></el-input>
              </el-form-item>
              <el-form-item label="现有标签">
                <div class="dialog-tag-list" style="line-height: 24px">
                  <el-tag
                    class="tag"
                    :key="item.id"
                    :disable-transitions="true"
                    v-for="(item) in labels"
                    closable
                    effect="dark"
                    size="mini"
                    @close="deleteLabel(item)"
                  >
                      {{item.tagName}}
                  </el-tag>
                </div>

              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="addLabel">添加</el-button>
                <el-button @click="$modal.hide('tagDialog')">取消</el-button>
              </el-form-item>
            </el-form>
        </el-card>
    </modal>
  </el-row>
</template>
<script>
import {mapMutations, mapState, mapActions} from 'vuex'
// import QuickReplies from '@/components/quickReplies';
import QuickReplies from './quick-replies';
import CustomDialog from '@/components/customDialog';
import Scenes from '@/lib/wechat-friend-scenes';
import group from '@/components/group'
import userWrapper from '@/components/user-wrapper'
import Clipboard from 'clipboard'
import messageButtonGroup from '@/components/message-button-group'

export default {
  name: 'userInfo',
  data() {
    return {
      editingLabel: '',
      mark: '',
      labels:[],
      groupInfo:{
        friendNum:0,
        personNum:0
      }
    }
  },
  mounted () {
  },
  computed: {
    ...mapState(['uistate','chatMap','friendMap']),
    currentUser(){
      const { chatid } = this.uistate
      const chat = this.chatMap[chatid]
      return chat
    },
    chat(){
      const { chatid } = this.uistate
      const chat = this.chatMap[chatid]
      return chat
    },
    isGroup(){
      const chat = this.chat
      if(!chat)return false
      const { friendwxid,friendid } = chat
      return friendwxid.endsWith('@chatroom')
    },
    source(){
      const chat = this.chat;
      if(!chat)return 0
      const { friendid } = chat
      const friend = this.friendMap[friendid]||{}
      return Scenes[friend.friendscene]
    }
  },
  components: {
    QuickReplies,
    CustomDialog,
    group,
    messageButtonGroup,
    userWrapper
  },
  watch:{
    'currentUser.friendremark'(val){
      this.mark = val
    },
    'uistate.chatid':function(newVal,oldVal){
      if(newVal&&newVal!==oldVal&&newVal!==-1){
        const chat = this.chatMap[this.uistate.chatid]||{}
        const csid = this.uistate.adminid
        const { wxaccount } = chat
        const friendwxid = chat.friendwxid||''
        this.$api.chat.friendTag({
          csId:csid,
          "friendAccount": friendwxid,
          "type": friendwxid.endsWith('@chatroom')?1:0,
          "wxAccount":wxaccount
        }).then(res=>{
          this.labels = res
        })
        if(this.isGroup){
          this.$api.group.groupInfo({
          csId:csid, wxAccount:wxaccount, groupNo:friendwxid
          })
          .then(res=>{
            console.log('groupInfo',res)
            if(res)
              this.groupInfo = {
                friendNum:res.friendNum,
                personNum:res.personnum,
                avatar:res.avatar
              }
              this.updateChatMap({id:this.uistate.chatid,isfirst:res.isfirst})
          })
        }

      }
    }
  },
  methods: {
    ...mapMutations(['pushReply', 'changeMessageInfo','updateChatMap','addMessageMap','addMessageListMap']),
    ...mapActions(['wsSend']),
    saveUserMark() {
      const { csid,wxaccount,friendwxid} = this.currentUser
      const params = {
        csId:csid,
        wxAccount:wxaccount,
        friendWxAccount:friendwxid,
        friendRemark:this.mark
      }


      this.$api.chat.editFriend(params)
        .then(res=>{
          this.$message({
            showClose: true,
            message: '保存成功',
            type: 'success'
          });
          this.updateChatMap({
            id:this.uistate.chatid,friendremark:this.mark
          })
        })

    },
    addLabel() {
      if (!this.editingLabel.trim()) return
      const chat = this.chatMap[this.uistate.chatid]||{}
      const { csid,friendwxid,wxaccount } = chat
      const isGroup = this.isGroup
      let params = { csid,tagname:this.editingLabel.trim(),"wxaccunt":wxaccount}
      if(isGroup){
        params.type = 1
        params.groupNo = friendwxid
      }else{
        params.type = 0
        params.friendAccount = friendwxid
      }
      this.$api.chat.insertFriendTag(params).then(res=>{
        if(res){

          this.labels.push({
            id:res,
            tagName:this.editingLabel
          })

          this.editingLabel = ''
          this.$modal.hide('tagDialog')
          console.log(this.labels)
        }

      })
      // currentUser.labels.push(this.editingLabel)
      // this.changeMessageInfo(currentUser)
    },
    copy(text, event){
      const clipboard = new Clipboard(event.target, {
        text: () => text
      })
      clipboard.on('success', () => {
        this.$message({
          showClose: true,
          message: '复制成功',
          type: 'success'
        });
        clipboard.destroy()
      })
      clipboard.on('error', () => {
        this.$message({
          showClose: true,
          message: '复制失败',
          type: 'error'
        });
        clipboard.destroy()
      })
      clipboard.onClick(event)
    },
    showEditLabelDialog() {
      this.$modal.show('tagDialog')
    },
    deleteLabel(label) {
      console.log(label)
      this.$api.chat.delFriendTag(label)
        .then(res=>{
          this.labels = this.labels.filter(item=>item.id!==label.id);
        })
    },

    addQucikReply(dialogType) {
      const data = this.form[dialogType];
      const type = /(\w+)QuickReply/g.exec(dialogType)[1];
      let reply
      if (type == 'text') {
        reply = {
          type,
          content: data
        }
      } else if (type == 'link') {
        reply = {
          type,
          url: data.url,
          title: data.title,
          content: data.content,
          cover: data.avatar
        }
      } else if (type == 'image') {
        reply = {
          type,
          src: data.avatar
        }
      } else if (type == 'contact') {
        reply = {
          type,
        }
      } else if (type == 'officalAccount') {
        reply = {
          type
        }
      }
      this.pushReply(reply)
    },
    quickClick(reply){
      const message = {...reply}
      const { csid,friendwxid,wxaccount,id } = this.currentUser;
      const { msgtype } = message;
      const msgId = +Date.now()
      delete message.id
      const msg = {
          wxAccount:wxaccount,
          msgId,
          msgid:msgId,
          friendId:friendwxid,
          msgType: msgtype,
          msgtype,
          opType: 1,
          content:JSON.stringify(message),
          chatfrom:1,
          sendstatus:-100,
          chatid:id
      }
      this.addMessageMap(msg)
      this.addMessageListMap(msg)
      this.wsSend(msg)

      console.log(reply,this.currentUser)
    },
    sendMessage(reply){

      const chatid = this.uistate.chatid
      const friendId = this.chatMap[chatid].friendwxid
      const wxAccount = this.chatMap[chatid].wxaccount

      const { csid,msgid,id,msgtype,content,src,title,url,link,wxid } = reply;
      const msgId = +Date.now()
      let message
      if(msgtype === 1){
        message = {
          content,msgtype
        }
      }else if(msgtype === 2){
        message = {
          src,msgtype
        }
      }else if(msgtype === 10){
        message = {
          title,
          src,
          msgtype,
          content,
          url
        }
      }else if(msgtype === 13){
        message = {
          src,
          msgtype,
          wxid,
          content,
          title
        }
      }else{
        message = {
          title:this.reply.title,
          src:'https://p2.img.cctvpic.com/photoworkspace/contentimg/2019/08/27/2019082713514553578.jpg',
          url:this.reply.url,
          msgtype,
          content:this.reply.content
        }
      }
      const msg = {
          wxAccount,
          msgId,
          msgid:msgId,
          friendId,
          msgType: msgtype,
          msgtype,
          opType: 1,
          content:JSON.stringify(message),
          chatfrom:1,
          sendstatus:-100,
          chatid
      }
      this.addMessageMap(msg)
      this.addMessageListMap(msg)
      this.wsSend(msg)
    },
    async editGroup(chat){
      try{
        const confirm = await this.$prompt('正在修改['+chat.friendNick+']名称', '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '放弃修改',
          inputPlaceholder: '请输入群名称'
        })
        const groupName = confirm.value
        if(!groupName){
          this.$message({
            type: 'error',
            message: '请输入群名称'
          });
          this.editGroup(chat)
          return
        }
        const { csid:csId,wxaccount:wxAccount,friendwxid:groupNo } = chat
        const params = {
          csId, wxAccount ,groupNo ,groupName
        }
        const result = await this.$api.group.setGroupName(params)
        this.$message({
            type: 'success',
            message: '提交成功，群名称将在5分钟内修改成功'
          });

      }catch(e){
        console.log(e)
      }
      console.log(chat)
    }
  }
}
</script>
<style lang="scss">

.infoContainer {
  .addQuickReply .layui-btn {
    margin-left: 5px !important;
  }
}
</style>
<style scoped>
.info-container {
    width: 350px;
    height: 100%;
    background: #f5f5f5;
    overflow: auto;
    user-select: none;
    flex-shrink: 0;
    flex-direction: column;
}
.info-inner{
  display: flex;
  height: 100%;
  flex-direction: column;
}
.box-card{
  margin: 0 10px 10px;
  flex-shrink: 0;
}

.info-card{
  margin-top: 10px;
}
.group{
  width: 100%;
}
.name-wrap{
  align-items: center;
  overflow: hidden;
}
.edit-group{
  flex-shrink: 0;
  color: #409EFF;
  margin-left: 10px;
}
.el-avatar{
  flex-shrink: 0
}

.box-card /deep/ .el-card__header{
  padding:10px 15px;
}
.box-card /deep/ .el-card__body{
  padding:10px 15px;
}
.box-card /deep/ .el-textarea__inner{
  padding:5px 5px;
}
.user-info{
  justify-content: space-around;
  display: flex;
  flex-direction: column;
  padding-left: 5px;
}
.source{
  margin-top: 10px;
  color: #999;
}
.source span{
  color: #333;
}
.wxid{
  margin-top: 10px;
  color: #999;
}
.wxid span{
  color: #333;
}
.wxid .el-link{
  margin-left: 5px;
}
.box-card-header{
  display: flex;
  align-items: center;
  justify-content:space-between;
}
.tag{
  margin-right: 5px;
}
.tag:first-child{
}
</style>
